package com.ctrip.corp.obt.shard.handler.strategy;

import com.ctrip.corp.obt.generic.utils.NumberUtils;
import com.ctrip.corp.obt.shard.configuration.DataShardProperties;

/**
 * @author marco.zheng
 * @version 1.0
 * @date 2022/02/09
 * @desc Hash表路由，根据tenantId并按照{@link DataShardProperties#getShardTableRange()}取模进行分表
 * @see
 * @since 1.0
 */
public class HashTableRouteStrategy implements ITableRouteStrategy {

    private final DataShardProperties properties;

    public HashTableRouteStrategy(DataShardProperties properties) {
        this.properties = properties;
    }

    @Override
    public String routeTable(String tenantId) {
        if (NumberUtils.isNumber(tenantId)) {
            return String.valueOf(NumberUtils.createInteger(tenantId) % properties.getShardTableRange());
        }
        return String.valueOf(tenantId.hashCode() % properties.getShardTableRange());
    }

    @Override
    public String strategyName() {
        return "hash";
    }

}
